package com.k.kpp.config.datasource.aop;

import com.k.kpp.config.datasource.DynamicDataSourceContextHolder;
import com.k.kpp.config.datasource.annotation.DataSourceSwitch;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切换处理器
 * Order(-1) 该切面应当先于 @Transactional 执行
 * @author k
 * @date May 12, 2012
 */
@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {

    /**
     * 切换数据源
     * @param point point
     * @param dataSourceSwitch Annotation obj
     */
    @Before("@annotation(dataSourceSwitch))")
    public void switchDataSource(JoinPoint point, DataSourceSwitch dataSourceSwitch) {
        if (!DynamicDataSourceContextHolder.containDataSourceKey(dataSourceSwitch.value())) {
            System.out.println("DataSource [{}] doesn't exist, use default DataSource [{}] " + dataSourceSwitch.value());
        } else {
            // 切换数据源
            DynamicDataSourceContextHolder.setDataSourceKey(dataSourceSwitch.value());
            System.out.println("Switch DataSource to [" + DynamicDataSourceContextHolder.getDataSourceKey()
                    + "] in Method [" + point.getSignature() + "]");
        }
    }

    /**
     * 重置数据源
     * @param point point
     * @param dataSourceSwitch Annotation obj
     */
    @After("@annotation(dataSourceSwitch))")
    public void restoreDataSource(JoinPoint point, DataSourceSwitch dataSourceSwitch) {
        // 将数据源置为默认数据源
        DynamicDataSourceContextHolder.clearDataSourceKey();
        System.out.println("Restore DataSource to [" + DynamicDataSourceContextHolder.getDataSourceKey()
                + "] in Method [" + point.getSignature() + "]");
    }
}
